<?php
$loader->requireOnce('includes/EwhValuatePrice/EwhValuateProc.class.php');
$loader->requireOnce('includes/EwhImport/EwhImportDrugMaterialProc.class.php');

/**
 * Controler for valuate drug/material prices.
 * @package modules.dept_pharmacy.controllers
 * @author viethd
 * @version $Id$
 * @copyright 2009 LHV Company
 */
class C_EwhValuator extends Controller {
    private $logger ;
    private $phaValuatePro;
    private $phaImportPro;
    function __construct($template_mod = "general") {
        parent::Controller();
        $this->logger = LoggerManager::getLogger('module.dept_pharmacy.controllers.C_EwhValuator');
        $this->template_mod = $template_mod;
        $this->view->path="pha_ewh_valuator";
        $this->phaValuatePro = new EwhValuateProc($this);
        $this->phaImportPro = new EwhImportDrugMaterialProc($this);
    }

    public function actionDisplayValuateByImTicket() {
        $this->logger->info('Start actionDisplayEditImTickPage');
        $this->assignDefaultValuate();
        $html = $this->view->render('valuate_imticket.html');
        $this->logger->info('Finish actionDisplayEditImTickPage');
        return $html;
    }

    private function assignDefaultValuate() {
        $orders =   L10nHelper::getYMDorder();
        $this->assign('datePart_0', $orders[0]);
        $this->assign('datePart_1', $orders[1]);
        $this->assign('datePart_2', $orders[2]);
        $this->assign('imTicket', null);
        $this->assign('createDate', null);
        $this->assign('listDMItems',null);
        $arrMethod = Utils::getEnumArrayKey(EnumerationConstant::PHA_VALUATE_METHOD);
        $this->assign('selectedMethod', EnumerationConstant::PHA_VALUATE_METHOD_LASTED_PRICE_KEY);
        $this->assign('arrMethod', $arrMethod);
    }

    public function actionDoSearchImTicketAjax() {
        $this->logger->info('Start actionEditImTicketAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        $fDate = '';
        $tDate = '';
        if ($_POST['fromDateyyyy'] != '' && $_POST['fromDatemm'] && $_POST['fromDatedd']) {
            $fDate = sprintf("%04s-%02s-%02s 00:00:00", $_POST['fromDateyyyy']
            , $_POST['fromDatemm'], $_POST['fromDatedd']);
        }
        if ($_POST['toDateyyyy'] != '' && $_POST['toDatemm'] && $_POST['toDatedd']) {
             
            $tDate = sprintf("%04s-%02s-%02s 23:59:59", $_POST['toDateyyyy']
            , $_POST['toDatemm'], $_POST['toDatedd']);
        }

        //only all the im ticket with this filter
        $filter = array(
            "imTicketCode"  =>  $_POST['imTicketCode'],
            "fromDate"      =>  $fDate,
            "toDate"        =>  $tDate,
            "valuated"        =>  '',
            "finalized"     => 0
        );

        $arrImTicket = $this->phaImportPro->searchImticket($filter);
        $this->assign('arrImTicket', $arrImTicket);
        $result['result'] = $this->view->render('valuate_imticket_search_result.html');
        $this->logger->info('Finish actionEditImTicketAjax');
        return json_encode($result);
    }

    public function actionLoadImTicket4ValuateAjax() {
        $this->logger->info('Start actionLoadImTicket4ValuateAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
         
        $imTicketId = $_POST['imTicketId'];
        try {
             
            $imTicketObj = $this->phaImportPro->getImTicketObj($imTicketId);
            $list = $this->phaValuatePro->getArrItemsOfImTicket($imTicketId);
            $this->assignDefaultValuate();
            $this->assign('imTicketCode', $imTicketObj->get('imticket_code'));
            $this->assign('imTicketId', $imTicketId);
            $this->assign('createDate', L10nHelper::renderDateTime($imTicketObj->get('date')));
            $this->assign('listDMItems', $list);
            $result['result'] = $this->view->render('valuate_area.html');
        } catch (EwhImportException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = EwhErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('actionEditImTicketAjax fail. Error detail: '. $ex->getMessage());
        } catch (Exception $ex) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error('actionEditImTicketAjax fail. Error detail: '. $ex->getMessage());

        }
        $this->logger->info('Finish actionLoadImTicket4ValuateAjax');
         
        return json_encode($result);
    }

    public function actionFinalizeImTicketAjax() {
        $this->logger->info('Start actionFinalizeImTicketAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        $imTicketId = $_POST['imTicketId'];
        try {
            $phaEwhImticketObj = Celini::newOrdo('PhaEwhImticket');
            if ($phaEwhImticketObj->canFinalize($imTicketId) == false) {
                throw new EwhValuateException('Could not finalize for imticket [' . $imTicketId . ']',
                EwhErrorCode::EVP_COULT_NOT_FINALIZE_IMTICKET);
            }  
            
            $phaEwhImticketObj->finalize($imTicketId);            
            
        } catch (EwhValuateException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = EwhErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('actionEditImTicketAjax fail. Error detail: '. $ex->getMessage());
        } catch (Exception $ex) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error('actionEditImTicketAjax fail. Error detail: '. $ex->getMessage());

        }
         
         
        $this->logger->info('Finish actionFinalizeImTicketAjax');
        return json_encode($result);
    }


    public function actionApplyValuationAjax() {
        $this->logger->info('Start actionApplyValuationAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        $valuatingItemIdList = array();
        $insurranceRate = 0;
        $serviceFeeRate = 0;
        $rateUnit = 0;
        $valuatedMethod = 0;
        $allowSell = 0;
        $imTicketId = 0;
        //array
        if (isset($_POST['drugMaterialImportedId'])) {
            $valuatingItemIdList = $_POST['drugMaterialImportedId'];
        }
        if (isset($_POST['insurranceRate'])) {
            $insurranceRate = $_POST['insurranceRate'];
        }
        if (isset($_POST['serviceFeeRate'])) {
            $serviceFeeRate = $_POST['serviceFeeRate'];
        }
        if (isset($_POST['rateUnit'])) {
            $rateUnit = $_POST['rateUnit'];
        }
        if (isset($_POST['valuatedMethod'])) {
            $valuatedMethod = $_POST['valuatedMethod'];
        }
        if (isset($_POST['allow_sell_all'])) {
            $allowSell = $_POST['allow_sell_all'];
        }
        if (isset($_POST['imTicketId'])) {
            $imTicketId = $_POST['imTicketId'];
        }

        try {
            $metaData = array(
                'imTicketId'    => $imTicketId,
                'valuator_user_id' => $this->_me->get_person_id(),        
                'date'             => date('Y-m-d H:i:s'),                
                'service_rate'      => $serviceFeeRate,
                'insurance_rate'    => $insurranceRate,
                'enum_rate_type'   =>  $rateUnit,
                'allow_sell'        => $allowSell
            );


            $this->phaValuatePro->valuate($valuatedMethod, $metaData, $valuatingItemIdList);

        } catch (EwhValuateException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = EwhErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('actionEditImTicketAjax fail. Error detail: '. $ex->getMessage());
        } catch (Exception $ex) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error('actionEditImTicketAjax fail. Error detail: '. $ex->getMessage());

        }


        $this->logger->info('Finish actionApplyValuationAjax');
        return json_encode($result);

    }

    public function actionAllowSellAjax() {
        $this->logger->info('Start actionAllowSellAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),'result'=>'');
        $imTicketId = $_POST['imTicketId'];
        $imTicketDetailId = $_POST['imTicketDetailId'];
        $allowSell = $_POST['allowSell'];
        $this->phaValuatePro->allowSell($imTicketId, $imTicketDetailId, $allowSell);
        $this->logger->info('Finish actionAllowSellAjax');
        return json_encode($result);

    }


}
?>